//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "fn_apply.sqf"
#include <btc_macros.h>
TRACE_1("Start",_this);

private ["_is_valid","_hint"];

_is_valid = true;
_hint = "";
// Add validity check here and display a hint of not valid then exit.
if (isnil "BTC_r_mobile_selected" || {typename BTC_r_mobile_selected != typename objNull} || {isNull BTC_r_mobile_selected} ) then {
	_is_valid = false;
	_hint = "Invalid Target";
} else {
	if (BTC_r_mobile_selected isKindOf "Man") then {
		if (_is_valid && {BTC_r_mobile_selected == player}) then { _is_valid = false; _hint = "Cannot respawn on yourself"; };
		if (_is_valid && {format ["%1", BTC_r_mobile_selected getVariable ["BTC_need_revive","0"]] != "0"}) then { _is_valid = false; _hint = "Target is waiting for revive"; };
	} else {
		if (_is_valid && {!alive BTC_r_mobile_selected}) then { _is_valid = false; _hint = "The vehicle is destroyed"; };
		if (_is_valid && {speed BTC_r_mobile_selected > 4}) then { _is_valid = false; _hint = "The vehicle is moving"; };
		if (_is_valid && {((getPos BTC_r_mobile_selected) select 2) > 5}) then { _is_valid = false; _hint = "The vehicle is flying"; };
	};
};

if (_is_valid) then {
	private ["_mobile","_empty_pos"];
	BTC_r_chosen = true;
	titleText ["", "BLACK OUT"];
	sleep 0.5;
	titleText ["", "BLACK FADED"];
	_empty_pos = (getMarkerPos BTC_respawn_marker);
	if (!isNull BTC_r_mobile_selected) then {
		_mobile = BTC_r_mobile_selected;
		_empty_pos = (position _mobile) findEmptyPosition [1,20];
		if (count _empty_pos <= 0) then { _empty_pos = _mobile modelToWorld [0,-4,0]; };
	} else {
		_empty_pos = (getMarkerPos BTC_respawn_marker) findEmptyPosition [1,20];
		if (count _empty_pos <= 0) then { _empty_pos = (getMarkerPos BTC_respawn_marker); };
	};
	TRACE_1("Target",ARR_2(_empty_pos,BTC_r_mobile_selected));
	if (!(isNull attachedTo player)) then {
		player attachTo [BTC_r_base_spawn,[0,0,0]];
		detach player;
	};
	player setPos _empty_pos;
	player setVelocity [0,0,0];
	sleep 0.1;
	player playMoveNow "amovpercmstpsraswrfldnon";
	titleText ["", "BLACK IN"];
	sleep 1;
	titleText ["", "PLAIN"];
} else {
	ctrlSetText [130, ">>>>  " + _hint + "  <<<<"];
	TRACE_1("Invalid",_this);
};
TRACE("End");